﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Net;
using Microsoft.Reporting.WebForms;
using System.Collections;
using System.Xml.Linq;
using Elmah.ContentSyndication;
using System.Diagnostics;
using OfficeOpenXml;
using System.Drawing;

/// <summary>
/// Common functions
/// </summary>
public class CommonUtil
{
    private const int MONDAY = 1;
    private const int TUESDAY = 2;
    private const int WEDNESDAY = 3;
    private const int THURSDAY = 4;
    private const int FRIDAY = 5;
    private const int SATURDAY = 6;
    private const int SUNDAY = 7;
    public static string[] mNos = new string[100];
    public CommonUtil()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static string GetRenderControl(Control oControl)    // comman render event for all control
    {

        StringWriter stringWriter = new StringWriter();

        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

        oControl.RenderControl(htmlWriter);

        return stringWriter.ToString();

    }

    /// <summary>
    /// Sends Error details to developer/support team
    /// </summary>
    /// <param name="con"></param>
    /// <returns></returns>
    public static bool Elmah_MailError(HttpContext con, string p_PageName = "")
    {
        string strErrorDtbl = "";
        System.Collections.IList errorList = new System.Collections.ArrayList();
        Elmah.ErrorLog.GetDefault(con).GetErrors(0, 1, errorList);
        if (errorList.Count > 0)
        {
            Elmah.ErrorLogEntry entry = errorList[0] as Elmah.ErrorLogEntry;
            DataTable dtblElmah = new DataTable();
            dtblElmah.Columns.Add("Name", typeof(string));
            dtblElmah.Columns.Add("Details", typeof(string));

            DataRow drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Host";
            drElmah["Details"] = entry.Error.HostName;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Code";
            drElmah["Details"] = entry.Error.StatusCode;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Type";
            drElmah["Details"] = entry.Error.Type;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Message";
            drElmah["Details"] = entry.Error.Message;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "User";
            drElmah["Details"] = entry.Error.User;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Date";
            drElmah["Details"] = entry.Error.Time;
            dtblElmah.Rows.Add(drElmah);
            drElmah = dtblElmah.NewRow();
            drElmah["Name"] = "Page";
            drElmah["Details"] = p_PageName;
            dtblElmah.Rows.Add(drElmah);
            dtblElmah.AcceptChanges();
            GridView grdElmah = new GridView();
            grdElmah.DataSource = dtblElmah;
            grdElmah.DataBind();
            strErrorDtbl = GetRenderControl(grdElmah);
        }

        string ReceiverEmail = GlobalDefaultValues.SupportTeamEmail;
        string subject = "Auditor Billing site Error";

        string strBody = "There is an error on " + System.DateTime.Now.ToString() + ". ";
        strBody += "<a href='" + System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
        if (System.Web.HttpContext.Current.Request.Url.Host == "localhost")
        {
            strBody += "/errorsgridview.aspx'>";
        }
        else
        {
            strBody += "/errorsgridview.aspx'>";
        }
        strBody += "click here" + "</a> to view errors.<br /><br />";
        strBody += strErrorDtbl;

        return SendMail(GlobalDefaultValues.FromEmailID, ReceiverEmail, subject, strBody, System.Web.Mail.MailFormat.Html, "", "true");
    }

    /// <summary>
    /// Sends Error details to developer/support team
    /// </summary>
    /// <param name="con"></param>
    /// <returns></returns>
    public static void Elmah_SignalException(Exception ex, HttpContext con, string p_PageName = "")
    {

        string sErrorTime = DateTime.Today.ToString("yyyyMMdd");
        string sFilePath = ErrorLogPhysicalPath();
        string sLogFormat = DateTime.Today.ToString("dd/MM/yyyy") + " " + DateTime.Now.ToLongTimeString().ToString();
        string sLoginName = "";// (SessionInfo.prop_getObj == null ? "" : SessionInfo.prop_getObj.EmployeeFullName);
        //if (HttpContext.Current == null)
        //    sFilePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "\\Error";//ConfigurationManager.AppSettings["Error_Service"].ToString();
        //else
        //    sFilePath = HttpContext.Current.Server.MapPath("~\\Error");



        try
        {
            CreateRequiredDirectories(sFilePath + "\\");
            sFilePath = sFilePath + "\\" + "ErrorLog";
            StreamWriter oWriter = new StreamWriter(sFilePath + sErrorTime + ".txt", true);

            #region Exception Detail
            string exp_desc = ex.Message.ToString();//exception description
            string exp_event = ex.TargetSite.ToString();//exception event
            string exp_type = ex.GetType().ToString();//exception type
            string exp_namespace = ex.GetType().Namespace.ToString();//exception namespace
            string exp_StackTrace = ex.StackTrace;//exception StackTrace

            StackTrace st1 = new StackTrace(ex, true);
            //StackFrame[] sfArr = st1.GetFrames();
            System.Reflection.MethodBase methodname = null;
            string exp_filename = string.Empty;
            string exp_Url = string.Empty;
            string exp_MethodName = string.Empty;
            int exp_lineNo = 0;
            int exp_ColumnNo = 0;
            string RefUrl = "";
            StackFrame sf = st1.GetFrame(st1.FrameCount - 1);
            if (!string.IsNullOrEmpty(sf.GetFileName()))
            {
                exp_filename = string.IsNullOrEmpty(sf.GetFileName()) ? "" : sf.GetFileName();//exception fileName
                exp_lineNo = sf.GetFileLineNumber();//exception Line No
                exp_ColumnNo = sf.GetFileColumnNumber();//exception Column No
                if (System.Web.HttpContext.Current != null)
                {
                    exp_Url = System.Web.HttpContext.Current.Request.Url.ToString();//exception fileName
                    RefUrl = (System.Web.HttpContext.Current.Request.UrlReferrer != null) ? System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString : "Not Available";//Referrer URL
                }
                else
                {
                    exp_Url = "Not Available";
                    RefUrl = "Not Available";
                }
                methodname = sf.GetMethod();//exception Event Name
                exp_MethodName = string.IsNullOrEmpty(methodname.Name) ? "" : methodname.Name;
            }
            else
            {
                StackFrame[] sfArr = st1.GetFrames();
                foreach (StackFrame sfobj in sfArr)
                {
                    if (string.IsNullOrEmpty(sfobj.GetFileName()))
                    {
                        exp_filename = string.IsNullOrEmpty(sfobj.GetFileName()) ? "" : sf.GetFileName();//exception fileName
                        exp_lineNo = sfobj.GetFileLineNumber();//exception Line No
                        exp_ColumnNo = sfobj.GetFileColumnNumber();//exception Column No
                        exp_Url = System.Web.HttpContext.Current.Request.Url.ToString();//exception fileName
                        RefUrl = (System.Web.HttpContext.Current.Request.UrlReferrer != null) ? System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString : "Not Available";//Referrer URL
                        methodname = sfobj.GetMethod();//exception Event Name
                        exp_MethodName = string.IsNullOrEmpty(methodname.Name) ? "" : methodname.Name;
                        break;
                    }
                }
            }
            #endregion
            oWriter.WriteLine(sLogFormat + " ==> " + sLoginName + " ==> " + exp_desc + " ==> " + exp_StackTrace + " ==> " + exp_lineNo + "\r\n\r\n");
            oWriter.Flush();
            oWriter.Close();
        }
        catch (Exception Ex)
        {
        }

        //Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        //Elmah_MailError(con, p_PageName);
    }

    /// <summary>
    /// Sends Error details to developer/support team
    /// </summary>
    /// <param name="con"></param>
    /// <returns></returns>
    public static bool SendMail(string pfrom, string pTo, string pSubject, string pBody, System.Web.Mail.MailFormat pFormat, string pAttachmentPath, string pssl)
    {
        try
        {
            MailAddress MailSender = new MailAddress(pfrom);
            MailMessage mailObj = new MailMessage();
            mailObj.From = MailSender;
            mailObj.To.Add(pTo);

            if (pAttachmentPath != null && pAttachmentPath != "")
            {
                string[] strAttachmentFiles = pAttachmentPath.Split(';');
                if (strAttachmentFiles.Length != 0)
                {
                    for (int index = 0; index < strAttachmentFiles.Length; index++)
                    {
                        if (File.Exists(strAttachmentFiles[index].ToString()))
                        {
                            System.Net.Mail.Attachment atch;
                            atch = new Attachment(strAttachmentFiles[index].ToString());
                            mailObj.Attachments.Add(atch);
                        }
                    }
                }
            }
            mailObj.Subject = pSubject;
            mailObj.Body = pBody;
            mailObj.IsBodyHtml = true;
            SmtpClient emailclient = new SmtpClient();
            emailclient.EnableSsl = GlobalDefaultValues.EnableSSL;
            emailclient.Send(mailObj);
            emailclient.Dispose();
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    /// <summary>
    ///  return System.Data.DataTable
    /// </summary>
    /// <param name="IEnum_InputObject">Ienumerable object to be converted into datatable</param>    
    public static DataTable GetIEnumerableToDatatable(IEnumerable<Object> IEnum_InputObject)
    {

        DataTable dt = new DataTable();

        foreach (object obj in IEnum_InputObject)
        {
            Type t = obj.GetType();
            PropertyInfo[] pis = t.GetProperties();
            if (dt.Columns.Count == 0)
            {
                foreach (PropertyInfo pi in pis)
                {
                    dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(
                    pi.PropertyType) ?? pi.PropertyType);
                }
            }
            DataRow dr = dt.NewRow();
            foreach (PropertyInfo pi in pis)
            {
                object value = pi.GetValue(obj, null);
                //dr[pi.Name] = value;
                dr[pi.Name] = (value == null ? DBNull.Value : value);
            }
            dt.Rows.Add(dr);
        }

        return (dt);

    }

    /// <summary>
    /// return System.Data.DataTable
    /// </summary>
    /// <param name="IEnum_InputObject">Ienumerable object to be converted into datatable</param>    
    public static DataTable GetObjectToDatatable(Object p_Object)
    {

        DataTable dt = new DataTable();

        Type t = p_Object.GetType();
        PropertyInfo[] pis = t.GetProperties();
        if (dt.Columns.Count == 0)
        {
            foreach (PropertyInfo pi in pis)
            {
                dt.Columns.Add(pi.Name, Nullable.GetUnderlyingType(
                pi.PropertyType) ?? pi.PropertyType);
            }
        }
        DataRow dr = dt.NewRow();
        foreach (PropertyInfo pi in pis)
        {
            object value = pi.GetValue(p_Object, null);
            dr[pi.Name] = (value == null ? DBNull.Value : value);
        }
        dt.Rows.Add(dr);
        return (dt);

    }

    /// <summary>
    /// return System.Data.DataTable
    /// </summary>
    /// <param name="IEnum_InputObject">Ienumerable object</param>
    /// <param name="outDataTableByRef">Datatable that need to be generated</param>
    /// <param name="p_strDateFormat">optional parameter to format date</param>
    public static void GetIEnumerableToDatatable(IEnumerable<Object> IEnum_InputObject, DataTable outDataTableByRef, string p_strDateFormat = "")
    {

        foreach (object obj in IEnum_InputObject)
        {
            Type t = obj.GetType();
            PropertyInfo[] pis = t.GetProperties();
            if (outDataTableByRef.Columns.Count == 0)
            {
                foreach (PropertyInfo pi in pis)
                {
                    outDataTableByRef.Columns.Add(pi.Name, Nullable.GetUnderlyingType(
                    pi.PropertyType) ?? pi.PropertyType);
                }
            }
            DataRow dr = outDataTableByRef.NewRow();
            foreach (PropertyInfo pi in pis)
            {
                object value = pi.GetValue(obj, null);
                if (pi.PropertyType.Name == "DateTime" && p_strDateFormat != "")
                    value = ((DateTime)value).ToString(p_strDateFormat);
                //dr[pi.Name] = value;
                dr[pi.Name] = (value == null ? DBNull.Value : value);
            }
            outDataTableByRef.Rows.Add(dr);
        }
    }

    /// <summary>
    /// Write error log text file
    /// </summary>
    /// <param name="msg">message to be write</param>
    /// <param name="fileName">file name </param>
    public static void LogMsg(string msg, string fileName)
    {
        TextWriter tw1;
        string path = HttpContext.Current.Server.MapPath(WebConfigurationManager.AppSettings["logPath"].ToString());
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        tw1 = new StreamWriter(path + "errLog_" + fileName + ".txt", true);
        tw1.WriteLine(msg);
        tw1.Flush();
        tw1.Close();
    }

    /// <summary>
    /// retrun current form name with extension
    /// </summary>
    /// <returns>from name with extension</returns>
    public static string GetCurrentFormName()
    {
        string p_AbsolutePath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
        System.IO.FileInfo oInfo = new System.IO.FileInfo(p_AbsolutePath);
        string sRet = oInfo.Name;
        return sRet;
    }

    /// <summary>
    /// Convert string value separated by comma into an integer array
    /// </summary>
    /// <param name="p_strSelectedValue"></param>
    /// <returns></returns>
    public static int[] getSplitSelectedValue(string p_strSelectedValue)
    {
        if (p_strSelectedValue != "")
        {
            string[] p_strSelectedValues = p_strSelectedValue.Split(',');
            int[] p_intSelectedValues = new int[p_strSelectedValues.Count()];
            for (int i = 0; i < p_strSelectedValues.Length; i++)
            {
                p_intSelectedValues[i] = TrynParse.parseInt(p_strSelectedValues[i]);
            }
            return p_intSelectedValues;
        }
        else
            return null;
    }

    public static string getIntArrayToString(int[] p_intArray)
    {
        if (p_intArray != null)
        {
            string p_strResult = "";
            for (int i = 0; i < p_intArray.Length; i++)
            {
                p_strResult = p_strResult + "," + p_intArray[i].ToString();
            }
            return p_strResult.Remove(0, 1);
        }
        else
            return "";
    }

    public static string CallbackResponse(object P_DictTCallbackResult, HttpResponse P_Response)
    {
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(P_DictTCallbackResult);
        return sJSON;
    }

    public static string CallbackResponseForOneRow(int p_intId, string p_strText)
    {
        string sJSON = "{\"id\":\"" + p_intId + "\",\"text\":\"" + p_strText + "\"}";
        return sJSON;
    }

    public static string CallbackResponseForOneRow(string p_strId, string p_strText)
    {
        string sJSON = "{\"id\":\"" + p_strId + "\",\"text\":\"" + p_strText + "\"}";
        return sJSON;
    }

    public static string GetTitleDropdownData()
    {
        string strTitleData = "[{\"id\":\"0\",\"text\":\"Select\"},{\"id\":\"Mr.\",\"text\":\"Mr.\"},{\"id\":\"Ms.\",\"text\":\"Ms.\"},{\"id\":\"Mrs.\",\"text\":\"Mrs.\"}]";
        return strTitleData;
    }

    /// <summary>
    /// Return date in format
    /// </summary>
    /// <param name="dtCurrentDay">datetime object to get in format</param>
    /// <returns>String object which is actually date in perticular format</returns>
    public static string GetDateFormatWithOrdinal(object p_objDate)
    {
        if (p_objDate != null)
        {
            DateTime objDate = TrynParse.parseDatetime(p_objDate);
            return AddOrdinal(objDate.Day) + objDate.ToString(" MMM yyyy");
        }
        else
            return "";
    }

    public static string GetDateFormatWithoutOrdinal(object p_objDate)
    {
        if (p_objDate != null)
        {
            DateTime objDate = TrynParse.parseDatetime(p_objDate);
            return objDate.ToString("dd MMM yyyy");
        }
        else
            return "";
    }

    /// <summary>
    /// Function to add ordinal to the date
    /// </summary>
    /// <param name="num">Date of the month to get proper ordinal</param>
    /// <returns>string object which is date with the ordinal</returns>
    public static string AddOrdinal(int num)
    {
        switch (num % 100)
        {
            case 11:
            case 12:
            case 13: return num.ToString() + "th";
        } switch (num % 10)
        {
            case 1:
                return num.ToString() + "st";
            case 2: return num.ToString() + "nd";
            case 3: return num.ToString() + "rd";
            default: return num.ToString() + "th";
        }
    }

    public static string CalenderDateFormat(DateTime? p_objDate)
    {
        if (p_objDate != null)
            return p_objDate.Value.ToString("dd/MM/yyyy");
        else
            return "";
    }

    /// <summary>
    /// Function to replace special characters with codes
    /// </summary>
    /// <param name="p_strText">string containing special characters</param>
    /// <returns></returns>
    public static string SpecialCharacterEncode(string p_strText)
    {
        char chCarrRet = (char)13;
        char chLineFeed = (char)10;
        char chTab = (char)9;
        string strRetJSONFriendly = p_strText.Replace("\"", "&#34;").Replace("'", "&#39;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\\", "&#92;").Replace("\r\n", "<br />").Replace("\r\n\t", "<br />      ").Replace("\t\r\n", "      <br />").Replace("  ", "").Replace(chCarrRet.ToString(), "<br />").Replace(chLineFeed.ToString(), "<br />").Replace(chTab.ToString(), "      "); /*.Replace("?", "&#63;").Replace("@", "&#64;").Replace("[", "&#91;").Replace("]", "&#93;").Replace("^", "&#94;").Replace("_", "&#95;").Replace("`", "&#96;").Replace("{", "&#123;").Replace("|", "&#124;").Replace("}", "&#125;").Replace("~", "&#126;").Replace("#", "&#35;").Replace("$", "&#36;").Replace("%", "&#37;").Replace("&", "&#38;").Replace("=", "&#61;").Replace("(", "&#40;").Replace(")", "&#41;").Replace("*", "&#42;").Replace("+", "&#43;").Replace(",", "&#44;").Replace("-", "&#45;").Replace(".", "&#46;").Replace("/", "&#47;").Replace(":", "&#58;").Replace(";", "&#59;");*/
        return strRetJSONFriendly;
    }

    /// <summary>
    /// Function to replace code with special characters
    /// </summary>
    /// <param name="p_strText">string containing code</param>
    /// <returns></returns>
    public static string SpecialCharacterDecode(string p_strText)
    {
        char chCarrRet = (char)13;
        char chLineFeed = (char)10;
        char chTab = (char)9;
        string strRetJSONFriendly = p_strText.Replace("&amp;", "&").Replace("&#34;", "\"").Replace("&#39;", "'").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&#92;", "\\").Replace("<br />", "\r\n").Replace("<br />      ", "\r\n\t").Replace("      <br />", "\t\r\n").Replace("<br />", chCarrRet.ToString()).Replace("<br />", chLineFeed.ToString()).Replace("      ", chTab.ToString()); /*.Replace("?", "&#63;").Replace("@", "&#64;").Replace("[", "&#91;").Replace("]", "&#93;").Replace("^", "&#94;").Replace("_", "&#95;").Replace("`", "&#96;").Replace("{", "&#123;").Replace("|", "&#124;").Replace("}", "&#125;").Replace("~", "&#126;").Replace("#", "&#35;").Replace("$", "&#36;").Replace("%", "&#37;").Replace("&", "&#38;").Replace("=", "&#61;").Replace("(", "&#40;").Replace(")", "&#41;").Replace("*", "&#42;").Replace("+", "&#43;").Replace(",", "&#44;").Replace("-", "&#45;").Replace(".", "&#46;").Replace("/", "&#47;").Replace(":", "&#58;").Replace(";", "&#59;");*/
        return strRetJSONFriendly;
    }

    /// <summary>
    /// Function to replace accented characters - replaces characters like “ö” with “o”, “è″ with “e” and “ñ” with “n”
    /// </summary>
    /// <param name="p_strText"></param>
    /// <returns></returns>
    public static string ReplaceDiacritics(string p_strText)
    {
        string strsourceInFormD = p_strText.Normalize(NormalizationForm.FormD);

        StringBuilder output = new StringBuilder();
        foreach (char c in strsourceInFormD)
        {
            UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
            if (uc != UnicodeCategory.NonSpacingMark)
                output.Append(c);
        }
        return (output.ToString().Normalize(NormalizationForm.FormC));
    }

    /// <summary>
    /// Get Uploaded file name
    /// </summary>
    /// <param name="p_pfFile">Posted file object</param>
    /// <returns>valid file name</returns>
    public static string GetUploadFileName(HttpPostedFile p_pfFile)
    {
        return System.Text.RegularExpressions.Regex.Replace(p_pfFile.FileName, @"[^0-9(?-i)a-z.]+", "_");
    }

    /// <summary>
    /// Get Property from the name of column
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="field"></param>
    /// <returns></returns>
    public static Func<T, DateTime> GetDateField<T>(string field)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(field);
        return obj => Convert.ToDateTime(propertyInfo.GetValue(obj, null));
    }
    public static Func<T, string> GetStringField<T>(string field)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(field);
        return obj => Convert.ToString(propertyInfo.GetValue(obj, null));
    }
    public static Func<T, double> GetDoubleField<T>(string field)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(field);
        return obj => Convert.ToDouble(propertyInfo.GetValue(obj, null));
    }
    public static Func<T, int> GetIntField<T>(string field)
    {
        PropertyInfo propertyInfo = typeof(T).GetProperty(field);
        return obj => Convert.ToInt32(propertyInfo.GetValue(obj, null));
    }

    /// <summary>
    /// Function to load dropdown, select default value
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="DDLtoBind">Dropdown Id</param>
    /// <param name="ComboLoader">Datasource</param>
    /// <param name="SelectedValue"></param>
    /// <param name="AppendItem">eg. => "Select [For]" </param>
    public static void LoadDropDown<T>(DropDownList DDLtoBind, Func<int, IEnumerable<T>> ComboLoader, int SelectedValue = 0, string AppendItem = null)
    {
        DDLtoBind.Items.Clear();

        DDLtoBind.DataSource = ComboLoader(SelectedValue);
        DDLtoBind.DataBind();

        if (AppendItem != null)
        {
            DDLtoBind.Items.Insert(0, AppendItem);
            DDLtoBind.Items[0].Value = "0";
        }
        DDLtoBind.SelectedValue = SelectedValue.ToString();
    }

    public static void LoadDropDown<T>(DropDownList DDLtoBind, Func<int, IEnumerable<T>> ComboLoader)
    {
        DDLtoBind.DataSource = ComboLoader(0);
        DDLtoBind.DataBind();
    }

    public static void LoadDropdown(DropDownList pObjDDL, object ComboLoader, string pStrValueField, string pStrTextField, string pStrInitValue = "", string pStrSelectedVal = "")
    {
        pObjDDL.DataSource = ComboLoader;
        pObjDDL.DataTextField = pStrTextField;
        pObjDDL.DataValueField = pStrValueField;
        pObjDDL.DataBind();
        if (pStrInitValue != "")
            pObjDDL.Items.Insert(0, new ListItem(pStrInitValue, "0"));
        if (pStrSelectedVal != "")
        {
            if (pObjDDL.Items.FindByValue(pStrSelectedVal) != null)
            {
                pObjDDL.ClearSelection();
                pObjDDL.SelectedValue = pStrSelectedVal;
            }
        }
    }

    public static string LoadDropdownOptions(DropDownList pObjDDL, object ComboLoader, string pStrValueField, string pStrTextField, string pStrInitValue = "", string pStrSelectedVal = "")
    {
        pObjDDL.DataSource = ComboLoader;
        pObjDDL.DataTextField = pStrTextField;
        pObjDDL.DataValueField = pStrValueField;
        pObjDDL.DataBind();
        if (pStrInitValue != "")
            pObjDDL.Items.Insert(0, new ListItem(pStrInitValue, "0"));
        if (pStrSelectedVal != "")
        {
            if (pObjDDL.Items.FindByValue(pStrSelectedVal) != null)
            {
                pObjDDL.ClearSelection();
                pObjDDL.SelectedValue = pStrSelectedVal;
            }
        }
        ListItem[] ListitemsArray = new ListItem[pObjDDL.Items.Count];
        pObjDDL.Items.CopyTo(ListitemsArray, 0);
        return string.Join("", ListitemsArray.Select(s => "<option value='" + s.Value + "'>" + s.Text + "</option>"));
    }

    public static DataTable ArrayToDataTable(Array ar)
    {

        DataTable dt = new DataTable();

        if (ar.Length <= 0) return dt;

        PropertyInfo[] properties = ar.GetValue(0).GetType().GetProperties();

        foreach (PropertyInfo property in properties)
        {
            DataColumn dc = dt.Columns.Add(property.Name, typeof(string));
        }
        foreach (object obj in ar)
        {
            DataRow dr = dt.NewRow();
            foreach (PropertyInfo property in properties)
            {
                dr[property.Name] = property.GetValue(obj, null);
            }
            dt.Rows.Add(dr);
        }


        return dt;
    }

    public static string GeneratePassword()
    {
        string strPwdchar = "abcdefghijklmnopqrstuvwxyz0123456789#+@&$ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string strPwd = "";
        Random rnd = new Random();
        for (int i = 0; i <= 7; i++)
        {
            int iRandom = rnd.Next(0, strPwdchar.Length - 1);
            strPwd += strPwdchar.Substring(iRandom, 1);
        }
        return strPwd;
    }

    public static string GetCurrencyFormat(object p_objAmount)
    {
        if (p_objAmount != null)
            return String.Format("{0:#,##0.00}", p_objAmount);
        else return "";
    }

    public static string GetCurrencyFormatWithoutDecimal(object p_objAmount)
    {
        if (p_objAmount != null)
            return String.Format("{0:#,##0}", p_objAmount);
        else return "";
        //NumberFormatInfo nfo = new NumberFormatInfo();
        //nfo.CurrencyGroupSeparator = ",";
        //// you are interested in this part of controlling the group sizes
        //nfo.CurrencyGroupSizes = new int[] { 3, 2 };
        //nfo.CurrencySymbol = "";
        //return TrynParse.parseDecimal(p_objAmount).ToString("c0", nfo);
    }

    public static string ConvertDatatableToXML(DataTable dt)
    {
        MemoryStream str = new MemoryStream();
        dt.WriteXml(str, true);
        str.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(str);
        string xmlstr;
        xmlstr = sr.ReadToEnd();
        return (xmlstr);
    }

    /// <summary>
    /// This function is used to check if user has access rights to particular form and session is expire or not.
    /// </summary>
    /// <param name="p_strFormId">Pass the Comma form id for multiple forms</param>
    public static bool CheckPermittedForm(string p_strFormID)
    {
        IEnumerable<PLMstFormMasters> objList = SessionInfo.prop_getObj.Menu;
        if (objList.Where(m => m.FormID == TrynParse.parseInt(p_strFormID)).Count() > 0)
            return true;
        else
            return false;
    }


    public static void UI_CheckFormAccessRights(string p_strFormID)
    {
        bool blnAccessRight = true;
        string[] strFormIDs = p_strFormID.Split(new char[] { ',' });
        if (SessionInfo.prop_getObj.EmployeeID != 0)
        {
            foreach (string strFormId in strFormIDs)
            {
                blnAccessRight = SessionInfo.prop_getObj.EmployeeID != 0 ? CheckPermittedForm(p_strFormID) : false;
            }
            if (!blnAccessRight)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
                HttpContext.Current.Response.End();
            }
        }
    }

    /// <summary>
    /// Function to get form rights
    /// </summary>
    /// <param name="p_strFormID"></param>
    /// <returns></returns>
    public static PLMstFormMasters CheckRightsForForm(string p_strFormID)
    {
        UI_CheckFormAccessRights(p_strFormID);
        IEnumerable<PLMstFormMasters> objList = SessionInfo.prop_getObj.Menu;
        PLMstFormMasters objRights = objList.Where(m => m.FormID == TrynParse.parseInt(p_strFormID)).SingleOrDefault();
        return objRights;
    }

    //public static usp_EmployeeMenu_Result CheckRightsForForms(string p_strFormID)
    //{
    //    usp_EmployeeMenu_Result objList = new usp_EmployeeMenu_Result();
    //    //bool blnAccessRight = true;
    //    string[] strFormIDs = p_strFormID.Split(new char[] { ',' });
    //    if (SessionInfo.prop_getObj.EmployeeID != 0)
    //    {
    //        foreach (string strFormId in strFormIDs)
    //        {

    //            IEnumerable<usp_EmployeeMenu_Result> objListResult = SessionInfo.prop_getObj.Menu;
    //            objList = objListResult.Where(m => m.MenuID == TrynParse.parseInt(p_strFormID)).SingleOrDefault();

    //            //blnAccessRight = SessionInfo.prop_getObj.EmployeeID != 0 ? CheckPermittedForm(p_strFormID) : false;
    //        }
    //    }
    //    //UI_CheckFormAccessRights(p_strFormID);
    //    //IEnumerable<usp_EmployeeMenu_Result> objList = SessionInfo.prop_getObj.Menu;

    //    return objList;
    //}

    //public static string GenerateReport(string p_strLocalReportPath, ArrayList p_arlDataSource, string p_strFileType, string p_strFilePath, string p_strFileServerPath, string p_strFileName, ArrayList p_arlReportParameter = null, bool enableimages = false)
    //{
    //    LocalReport localReport = new LocalReport();
    //    localReport.ReportPath = p_strLocalReportPath;
    //    localReport.EnableExternalImages = enableimages;
    //    foreach (ReportDataSource rptDataSource in p_arlDataSource)
    //    {
    //        localReport.DataSources.Add(rptDataSource);
    //    }
    //    if (p_arlReportParameter != null)
    //    {
    //        foreach (ReportParameter rptParameter in p_arlReportParameter)
    //        {
    //            localReport.SetParameters(rptParameter);
    //        }
    //    }
    //    string reportType = p_strFileType; //PDF:for pdf,  Excel:for EXCEL, Image: for IMAGE
    //    Warning[] warnings;
    //    string[] streamIds;
    //    string mimeType = string.Empty;
    //    string encoding = string.Empty;
    //    string extension = string.Empty;
    //    string deviceInfo = "<DeviceInfo>" +
    //                "  <OutputFormat>" + reportType + "</OutputFormat>" +
    //                "  <PageWidth>8.5in</PageWidth>" +
    //                "  <PageHeight>11in</PageHeight>" +
    //                "  <MarginTop>0.5in</MarginTop>" +
    //                "  <MarginLeft>0.5in</MarginLeft>" +
    //                "  <MarginRight>0.5in</MarginRight>" +
    //                "  <MarginBottom>0.5in</MarginBottom>" +
    //                "</DeviceInfo>";

    //    byte[] bytes = localReport.Render(p_strFileType, deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);
    //    DirectoryInfo dir = new DirectoryInfo(p_strFileServerPath);
    //    if (dir.Exists == false)
    //    {
    //        dir.Create();
    //    }
    //    string strCurrentTime = DateTime.Now.ToString("ddMMyyyyhhmmss");
    //    string strFile = p_strFilePath + @"/" + p_strFileName;
    //    FileStream fs = new FileStream(p_strFileServerPath + "//" + p_strFileName, FileMode.Create);
    //    fs.Write(bytes, 0, bytes.Length);
    //    fs.Close();
    //    return strFile;
    //}

    //public static void GeneratePDFReport(HttpResponse p_PageResponse, string p_strLocalReportPath, ArrayList p_arlDataSource, string p_strFileType, string p_strFilePath, string p_strFileServerPath, string p_strFileName, ArrayList p_arlReportParameter = null, bool enableimages = false, string deviceInfo = "", bool blnRequiredSave = false)
    //{
    //    LocalReport localReport = new LocalReport();
    //    localReport.ReportPath = p_strLocalReportPath;
    //    localReport.EnableExternalImages = enableimages;
    //    foreach (ReportDataSource rptDataSource in p_arlDataSource)
    //    {
    //        localReport.DataSources.Add(rptDataSource);
    //    }
    //    if (p_arlReportParameter != null)
    //    {
    //        foreach (ReportParameter rptParameter in p_arlReportParameter)
    //        {
    //            localReport.SetParameters(rptParameter);
    //        }
    //    }
    //    string reportType = p_strFileType; //PDF:for pdf,  Excel:for EXCEL, Image: for IMAGE
    //    Warning[] warnings;
    //    string[] streamIds;
    //    string mimeType = string.Empty;
    //    string encoding = string.Empty;
    //    string extension = string.Empty;
    //    if (deviceInfo == "")
    //    {
    //        deviceInfo = "<DeviceInfo>" +
    //                    "  <OutputFormat>" + reportType + "</OutputFormat>" +
    //                    "  <PageWidth>8.5in</PageWidth>" +
    //                    "  <PageHeight>11in</PageHeight>" +
    //                    "  <MarginTop>0.5in</MarginTop>" +
    //                    "  <MarginLeft>0.5in</MarginLeft>" +
    //                    "  <MarginRight>0.5in</MarginRight>" +
    //                    "  <MarginBottom>0.5in</MarginBottom>" +
    //                    "</DeviceInfo>";
    //    }
    //    byte[] bytes = localReport.Render(p_strFileType, deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);

    //    if (blnRequiredSave == false)
    //    {
    //        p_PageResponse.ContentType = "application/force-download";
    //        p_PageResponse.Buffer = true;
    //        p_PageResponse.ContentType = mimeType;
    //        p_PageResponse.AddHeader("content-disposition", "attachment; filename= " + p_strFileName);
    //        if (bytes != null)
    //            p_PageResponse.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    //        p_PageResponse.End();
    //    }
    //    else
    //    {
    //        DirectoryInfo dir = new DirectoryInfo(p_strFileServerPath);
    //        if (dir.Exists == false)
    //        {
    //            dir.Create();
    //        }
    //        string strCurrentTime = DateTime.Now.ToString("ddMMyyyyhhmmss");
    //        string strFile = p_strFilePath + @"/" + p_strFileName;
    //        FileStream fs = new FileStream(p_strFileServerPath + "//" + p_strFileName, FileMode.Create);
    //        fs.Write(bytes, 0, bytes.Length);
    //        fs.Close();
    //    }

    //}

    public static string DHTMLXEmptyDataTemplate(string p_strColspan, string p_strMsg = "")
    {
        XElement xEle = new XElement("cell", new XAttribute("colspan", p_strColspan), new XAttribute("align", "center"), new XAttribute("style", "height:30px"), new XAttribute("type", "ro"), new XCData(p_strMsg == "" ? "No Records Found" : p_strMsg));
        var result = new XElement("rows", new XElement("row", xEle));
        return result.ToString().Replace("<rows>", "");
    }

    public static DataTable BindDdlYear(int? p_intStartYearFrom = null)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Year");
        for (int i = (p_intStartYearFrom ?? 1950); i <= System.DateTime.Now.Year; i++)
        {
            dt.Rows.Add(i);
        }

        return dt;
    }

    public static DataTable BindDdlMonth()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Month");
        dt.Columns.Add("ID");

        for (int i = 1; i <= 12; i++)
        {
            DataRow dr = dt.NewRow();
            System.Globalization.DateTimeFormatInfo nm = new System.Globalization.DateTimeFormatInfo();
            dr[0] = nm.GetMonthName(i);
            dr[1] = i;
            dt.Rows.Add(dr);
        }
        return dt;
    }

    public static DataTable BindDdlPeriod()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Period");
        dt.Columns.Add("ID");
        int intStartMonth = 1;//Jan
        int intStartYear = 2014;//2014
        int intEndMonth = DateTime.Now.AddMonths(1).Month;
        int intEndYear = DateTime.Now.AddMonths(1).Year;

        for (int j = intEndYear; j >= intStartYear; j--)
        {
            for (int i = 12; i >= 1; i--)
            {
                if (j == intEndYear && i > intEndMonth)
                    continue;

                if (j == intStartYear && i < intStartMonth)
                    break;

                DataRow dr = dt.NewRow();
                System.Globalization.DateTimeFormatInfo nm = new System.Globalization.DateTimeFormatInfo();
                dr[0] = nm.GetMonthName(i) + '-' + j.ToString();
                dr[1] = i.ToString() + '-' + j.ToString();
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }

    public static DataTable BindDdlDate()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Date");
        for (int i = 1; i <= 31; i++)
        {
            dt.Rows.Add(i);
        }

        return dt;
    }

    public static void IsValidDateTimeTest(string dateTime, out DateTime? parsedDateTime, out bool result)
    {
        string[] formats = { "dd/MM/yyyy", "d/M/yyyy", "dd/M/yyyy, M/dd/yyyy" };
        DateTime parsedDateTimeVal;
        result = DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDateTimeVal);
        parsedDateTime = parsedDateTimeVal;
    }

    public static void DisableBrowserBack()
    {
        HttpContext.Current.Response.Cache.SetNoStore();
        HttpContext.Current.Response.Cache.AppendCacheExtension("no-cache");
        HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddHours(-10));
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }

    public static void UI_RedirectToLogin()
    {
        FormsAuthentication.SignOut();
        HttpContext.Current.Session.Clear();
        HttpContext.Current.Session.Abandon();
        FormsAuthentication.RedirectToLoginPage();
        HttpContext.Current.Response.Redirect("Login.aspx");
    }

    public static string ColumnIndexToColumnLetter(int colIndex)
    {
        int div = colIndex;
        string colLetter = String.Empty;
        int mod = 0;

        while (div > 0)
        {
            mod = (div - 1) % 26;
            colLetter = (char)(65 + mod) + colLetter;
            div = (int)((div - mod) / 26);
        }
        return colLetter;
    }

    public static string NumberInDigits(int p_number, int p_digits)
    {
        string strNumber = p_number.ToString();
        if (strNumber.Length < p_digits)
        {
            while (strNumber.Length < p_digits)
            {
                strNumber = "0" + strNumber;
            }
        }

        return strNumber;
    }

    public static void GetWeekendDaysBetween(DateTime startDate, DateTime endDate, out int saturdays, out int sundays)
    {
        saturdays = -1;
        sundays = -1;
        if (endDate < startDate)
            return;
        TimeSpan timeBetween = endDate.Subtract(startDate);
        int weekendsBetween = timeBetween.Days / 7;
        sundays = weekendsBetween;
        saturdays = weekendsBetween;
        int startDay = GetDayOfWeekNumber(startDate.DayOfWeek);
        int endDay = GetDayOfWeekNumber(endDate.DayOfWeek);
        if (startDay > endDay)
        {
            sundays++;
            saturdays += (startDay < SUNDAY) ? 1 : 0;
        }
        else if (startDay < endDay)
        {
            //We don't have to care about sundays here, since we are excluding the last day
            //There will only be another saturday, if the end day is a sunday
            saturdays += (endDay == SUNDAY) ? 1 : ((endDay == SATURDAY) ? 1 : 0);
        }
    }

    private static int GetDayOfWeekNumber(DayOfWeek day)
    {
        switch (day)
        {
            case DayOfWeek.Monday:
                return MONDAY;
            case DayOfWeek.Tuesday:
                return TUESDAY;
            case DayOfWeek.Wednesday:
                return WEDNESDAY;
            case DayOfWeek.Thursday:
                return THURSDAY;
            case DayOfWeek.Friday:
                return FRIDAY;
            case DayOfWeek.Saturday:
                return SATURDAY;
            case DayOfWeek.Sunday:
                return SUNDAY;
            default:
                throw new ArgumentException("Invalid day!");
        }
    }

    public static int? CalculateCompletedAge(DateTime? dtDOB)
    {
        if (dtDOB != null)
        {
            DateTime today = DateTime.Today;
            int age = today.Year - dtDOB.Value.Year;
            if (dtDOB > today.AddYears(-age))
                age--;
            return age;
        }
        else
        {
            return null;
        }
    }

    public static string GetSuffix(string day)
    {
        string suffix = "th";

        if (int.Parse(day) < 11 || int.Parse(day) > 20)
        {
            day = day.ToCharArray()[day.ToCharArray().Length - 1].ToString();
            switch (day)
            {
                case "1":
                    suffix = "st";
                    break;
                case "2":
                    suffix = "nd";
                    break;
                case "3":
                    suffix = "rd";
                    break;
            }
        }

        return suffix;
    }

    public static DataTable BindDdlYearwise(int p_intStartYearFrom)
    {
        DateTime dtStartDate = new DateTime(2015, 04, 01);
        DateTime dtEndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        DateTime dtCurrentDate = dtEndDate;
        DataRow dr;
        DataTable dt = new DataTable();
        dt.Columns.Add("Period");
        dt.Columns.Add("ID");

        while (dtCurrentDate >= dtStartDate)
        {
            dr = dt.NewRow();
            System.Globalization.DateTimeFormatInfo nm = new System.Globalization.DateTimeFormatInfo();
            dr[0] = dtCurrentDate.ToString("MMMM-yyyy");
            dr[1] = dtCurrentDate.ToString("MM-yyyy");
            dt.Rows.Add(dr);
            dtCurrentDate = dtCurrentDate.AddMonths(-1);
        }

        //int intEndMonth = DateTime.Now.AddMonths(1).Month;
        //int intEndYear = DateTime.Now.AddMonths(1).Year;

        //DateTime dtStartDayOfYear = new DateTime(p_intStartYearFrom, 1, 1);
        //for (int d = intEndMonth; d >= 1; d--)
        //{
        //    DataRow dr = dt.NewRow();
        //    System.Globalization.DateTimeFormatInfo nm = new System.Globalization.DateTimeFormatInfo();
        //    dr[0] = nm.GetMonthName(d) + "-" + dtStartDayOfYear.Year;
        //    dr[1] = d.ToString() + "-" + dtStartDayOfYear.Year;
        //    dt.Rows.Add(dr);
        //}
        return dt;
    }

    public static string Amt2Wrds(double Amount, string p_currency, string p_fraction)
    {

        string mStrAmt = "", mChrAmt, amtInWords = "";
        int mLenAmt, mAmt;
        mNos[0] = "Zero";
        mNos[1] = "One";
        mNos[2] = "Two";
        mNos[3] = "Three";
        mNos[4] = "Four";
        mNos[5] = "Five";
        mNos[6] = "Six";
        mNos[7] = "Seven";
        mNos[8] = "Eight";
        mNos[9] = "Nine";
        mNos[10] = "Ten";
        mNos[11] = "Eleven";
        mNos[12] = "Twelve";
        mNos[13] = "Thirteen";
        mNos[14] = "Fourteen";
        mNos[15] = "Fifteen";
        mNos[16] = "Sixteen";
        mNos[17] = "Seventeen";
        mNos[18] = "Eighteen";
        mNos[19] = "Nineteen";
        mNos[20] = "Twenty";
        mNos[21] = "Twenty One";
        mNos[22] = "Twenty Two";
        mNos[23] = "Twenty Three";
        mNos[24] = "Twenty Four";
        mNos[25] = "Twenty Five";
        mNos[26] = "Twenty Six";
        mNos[27] = "Twenty Seven";
        mNos[28] = "Twenty Eight";
        mNos[29] = "Twenty Nine";
        mNos[30] = "Thirty";
        mNos[31] = "Thirty One";
        mNos[32] = "Thirty Two";
        mNos[33] = "Thirty Three";
        mNos[34] = "Thirty Four";
        mNos[35] = "Thirty Five";
        mNos[36] = "Thirty Six";
        mNos[37] = "Thirty Seven";
        mNos[38] = "Thirty Eight";
        mNos[39] = "Thirty Nine";
        mNos[40] = "Forty";
        mNos[41] = "Forty One";
        mNos[42] = "Forty Two";
        mNos[43] = "Forty Three";
        mNos[44] = "Forty Four";
        mNos[45] = "Forty Five";
        mNos[46] = "Forty Six";
        mNos[47] = "Forty Seven";
        mNos[48] = "Forty Eight";
        mNos[49] = "Forty Nine";
        mNos[50] = "Fifty";
        mNos[51] = "Fifty One";
        mNos[52] = "Fifty Two";
        mNos[53] = "Fifty Three";
        mNos[54] = "Fifty Four";
        mNos[55] = "Fifty Five";
        mNos[56] = "Fifty Six";
        mNos[57] = "Fifty Seven";
        mNos[58] = "Fifty Eight";
        mNos[59] = "Fifty Nine";
        mNos[60] = "Sixty";
        mNos[61] = "Sixty One";
        mNos[62] = "Sixty Two";
        mNos[63] = "Sixty Three";
        mNos[64] = "Sixty Four";
        mNos[65] = "Sixty Five";
        mNos[66] = "Sixty Six";
        mNos[67] = "Sixty Seven";
        mNos[68] = "Sixty Eight";
        mNos[69] = "Sixty Nine";
        mNos[70] = "Seventy";
        mNos[71] = "Seventy One";
        mNos[72] = "Seventy Two";
        mNos[73] = "Seventy Three";
        mNos[74] = "Seventy Four";
        mNos[75] = "Seventy Five";
        mNos[76] = "Seventy Six";
        mNos[77] = "Seventy Seven";
        mNos[78] = "Seventy Eight";
        mNos[79] = "Seventy Nine";
        mNos[80] = "Eighty";
        mNos[81] = "Eighty One";
        mNos[82] = "Eighty Two";
        mNos[83] = "Eighty Three";
        mNos[84] = "Eighty Four";
        mNos[85] = "Eighty Five";
        mNos[86] = "Eighty Six";
        mNos[87] = "Eighty Seven";
        mNos[88] = "Eighty Eight";
        mNos[89] = "Eighty Nine";
        mNos[90] = "Ninety";
        mNos[91] = "Ninety One";
        mNos[92] = "Ninety Two";
        mNos[93] = "Ninety Three";
        mNos[94] = "Ninety Four";
        mNos[95] = "Ninety Five";
        mNos[96] = "Ninety Six";
        mNos[97] = "Ninety Seven";
        mNos[98] = "Ninety Eight";
        mNos[99] = "Ninety Nine";
        string[] strSplit = Amount.ToString().Split('.');

        if (strSplit.Length > 1)
        {
            string val1 = strSplit[0];
            string val2 = strSplit[1];
            if (val2.Length == 1)
            {
                mStrAmt = Amount.ToString("######.#0");
            }
            else
            {
                mStrAmt = Amount.ToString("######.##");
            }
        }
        else
        {
            mStrAmt = Amount.ToString("######.00");
        }

        int mStrAmtlen = mStrAmt.Length;
        mAmt = int.Parse(mStrAmt.Substring(0, mStrAmtlen - 3));

        mChrAmt = mStrAmt.Substring(mStrAmtlen - 2);
        mLenAmt = mAmt.ToString().Length;
        if (mAmt == 0)
            mLenAmt = 0;

        if (mLenAmt == 0)
        {
            amtInWords = amtInWords + "Zero ";
        }
        else
        {
            if (mLenAmt > 9)
                return "";
            if (mLenAmt > 7)
            {
                amtInWords = amtInWords + AmtCnvrt("", int.Parse(mAmt.ToString().Substring(0, (mAmt.ToString().Length - 7))), "Million ");
                mAmt = int.Parse(mAmt.ToString().Substring(mAmt.ToString().Length - 7));
                mLenAmt = mAmt.ToString().Length;
            }
            if (mLenAmt > 5)
            {
                amtInWords = amtInWords + AmtCnvrt("", int.Parse(mAmt.ToString().Substring(0, (mAmt.ToString().Length - 5))), "Lakh ");
                mAmt = int.Parse(mAmt.ToString().Substring(mAmt.ToString().Length - 5));
                mLenAmt = mAmt.ToString().Length;
            }
            if (mLenAmt > 3)
            {
                amtInWords = amtInWords + AmtCnvrt("", int.Parse(mAmt.ToString().Substring(0, (mAmt.ToString().Length - 3))), "Thousand ");
                mAmt = int.Parse(mAmt.ToString().Substring(mAmt.ToString().Length - 3));
                mLenAmt = mAmt.ToString().Length;
            }
            if (mLenAmt == 3)
            {
                amtInWords = amtInWords + AmtCnvrt("", int.Parse(mAmt.ToString().Substring(0, (mAmt.ToString().Length - 2))), "Hundred ");
                mAmt = int.Parse(mAmt.ToString().Substring(mAmt.ToString().Length - 2));
                mLenAmt = mAmt.ToString().Length;
            }
            if (mLenAmt < 3 && mAmt != 0)
            {
                amtInWords = amtInWords + AmtCnvrt("", mAmt, "");
            }
            if (double.Parse(mChrAmt.Substring(0, 1)) > 0)
            {
                amtInWords = amtInWords + p_currency + " And ";
                amtInWords = amtInWords + AmtCnvrt("", int.Parse(mChrAmt), p_fraction + " Only.");
            }
            else
            {
                amtInWords = p_currency + amtInWords + "Only";
            }

        }
        return amtInWords;
    }
    public static string AmtCnvrt(string Rs, int pNo, string pStr)
    {

        return Rs + " " + mNos[pNo] + " " + pStr;
    }

    /// <summary>
    /// Insurance policy set ToDate From date function
    /// </summary>
    /// <param name="p_Day"></param>
    /// <param name="p_month"></param>
    /// <returns></returns>
    public static DateTime UI_SetDate(int p_Day, int p_month)
    {
        DateTime dtToDate = new DateTime(1900, p_month, p_Day);
        DateTime dtTodayDate;
        int Day = DateTime.Now.Day;
        int Month = DateTime.Now.Month;
        dtTodayDate = new DateTime(1900, Month, Day);
        int ToYear;

        if (dtTodayDate > dtToDate)
            ToYear = DateTime.Now.Year + 1;
        else
            ToYear = DateTime.Now.Year;

        return new DateTime(ToYear, p_month, p_Day);
    }

    public  void CreateErrorLogFile(string sModuleSource, Exception ex)
    {
        string sFilePath = ErrorLogPhysicalPath();
        //if (HttpContext.Current == null)
        //    sFilePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "\\Error";//ConfigurationManager.AppSettings["Error_Service"].ToString();
        //else
        //    sFilePath = HttpContext.Current.Server.MapPath("~\\Error");

        try
        {
            CreateRequiredDirectories(sFilePath + "\\");
            sFilePath = sFilePath + "\\" + "ErrorLog";
            StreamWriter oWriter = new StreamWriter(sFilePath + DateTime.Now.ToString("yy_MM_yy HH_mm_ss ") + sModuleSource + ".txt", true);

            #region Exception Detail
            string exp_desc = ex.Message.ToString();//exception description
            string exp_event = ex.TargetSite.ToString();//exception event
            string exp_type = ex.GetType().ToString();//exception type
            string exp_namespace = ex.GetType().Namespace.ToString();//exception namespace
            string exp_StackTrace = ex.StackTrace;//exception StackTrace

            StackTrace st1 = new StackTrace(ex, true);
            //StackFrame[] sfArr = st1.GetFrames();
            System.Reflection.MethodBase methodname = null;
            string exp_filename = string.Empty;
            string exp_Url = string.Empty;
            string exp_MethodName = string.Empty;
            int exp_lineNo = 0;
            int exp_ColumnNo = 0;
            string RefUrl = "";
            StackFrame sf = st1.GetFrame(st1.FrameCount - 1);
            if (!string.IsNullOrEmpty(sf.GetFileName()))
            {
                exp_filename = string.IsNullOrEmpty(sf.GetFileName()) ? "" : sf.GetFileName();//exception fileName
                exp_lineNo = sf.GetFileLineNumber();//exception Line No
                exp_ColumnNo = sf.GetFileColumnNumber();//exception Column No
                if (System.Web.HttpContext.Current != null)
                {
                    exp_Url = System.Web.HttpContext.Current.Request.Url.ToString();//exception fileName
                    RefUrl = (System.Web.HttpContext.Current.Request.UrlReferrer != null) ? System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString : "Not Available";//Referrer URL
                }
                else
                {
                    exp_Url = "Not Available";
                    RefUrl = "Not Available";
                }
                methodname = sf.GetMethod();//exception Event Name
                exp_MethodName = string.IsNullOrEmpty(methodname.Name) ? "" : methodname.Name;
            }
            else
            {
                StackFrame[] sfArr = st1.GetFrames();
                foreach (StackFrame sfobj in sfArr)
                {
                    if (string.IsNullOrEmpty(sfobj.GetFileName()))
                    {
                        exp_filename = string.IsNullOrEmpty(sfobj.GetFileName()) ? "" : sf.GetFileName();//exception fileName
                        exp_lineNo = sfobj.GetFileLineNumber();//exception Line No
                        exp_ColumnNo = sfobj.GetFileColumnNumber();//exception Column No
                        exp_Url = System.Web.HttpContext.Current.Request.Url.ToString();//exception fileName
                        RefUrl = (System.Web.HttpContext.Current.Request.UrlReferrer != null) ? System.Web.HttpContext.Current.Request.UrlReferrer.OriginalString : "Not Available";//Referrer URL
                        methodname = sfobj.GetMethod();//exception Event Name
                        exp_MethodName = string.IsNullOrEmpty(methodname.Name) ? "" : methodname.Name;
                        break;
                    }
                }
            }
            #endregion
            oWriter.WriteLine(exp_desc + " ==> " + exp_StackTrace + " ==> " + exp_lineNo);
            oWriter.Flush();
            oWriter.Close();

        }
        catch (Exception Ex)
        {
        }
    }
    public static string ErrorLogPhysicalPath()
    {
        string sFilePath = "";
        if (HttpContext.Current == null)
            sFilePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + "\\Error";//ConfigurationManager.AppSettings["Error_Service"].ToString();
        else
            sFilePath = HttpContext.Current.Server.MapPath("~\\Error");

        return sFilePath;
    }
    public static void CreateRequiredDirectories(string sFilePath)
    {
        bool bDirectoryExist = false;

        bDirectoryExist = Directory.Exists(sFilePath);
        if (!bDirectoryExist)
        {
            Directory.CreateDirectory(sFilePath);
        }
    }

    public static DateTime? fnGetDateFromJSFile(object pObjDate)
    {
        string[] strDateParts = pObjDate.ToString().Split('/');
        if (strDateParts.Length == 3)
        {
            return new DateTime(TrynParse.parseInt(strDateParts[2]), TrynParse.parseInt(strDateParts[1]), TrynParse.parseInt(strDateParts[0]));
        }
        else
            return null;
    }
    public static decimal? fnGetNumericFromJSFile(object pObjDate)
    {
        if (Convert.ToString(pObjDate) != "")
        {
            return TrynParse.parseDecimal(pObjDate);
        }
        else
            return null;
    }

    public static void ExportToExcelWithEPPlus(List<string> pStrArrHeaderLines, DataTable pDataTable, HttpResponse pPageResponse, string pStrFileName)
    {
        ExcelPackage excel = new ExcelPackage();
        var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
        int intStartIndex = 1;
        workSheet.Cells[pStrArrHeaderLines.Count + 2, 1].LoadFromDataTable(pDataTable, true);
        workSheet.Cells.AutoFitColumns();
        foreach (string strHeaderLine in pStrArrHeaderLines)
        {
            workSheet.Cells[intStartIndex++, 1].Value = strHeaderLine;
        }

        using (var memoryStream = new MemoryStream())
        {
            pPageResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            pPageResponse.AddHeader("content-disposition", "attachment;  filename=" + pStrFileName + ".xlsx");
            excel.SaveAs(memoryStream);
            memoryStream.WriteTo(pPageResponse.OutputStream);
            pPageResponse.Flush();
            pPageResponse.End();
        }
    }

    public static void ExportToExcelWithEPPlus<T>(List<string> pStrArrHeaderLines, IEnumerable<T> pResult, HttpResponse pPageResponse, string pStrFileName)
    {
        ExcelPackage excel = new ExcelPackage();
        var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
        int intStartIndex = 1;
        workSheet.Cells[2, 1].LoadFromCollection(pResult, false);
        workSheet.Cells.AutoFitColumns();
        foreach (string strHeaderLine in pStrArrHeaderLines)
        {
            workSheet.Cells[1, intStartIndex++].Value = strHeaderLine;
        }
        Export_AlignAndSetStyleForSheet(workSheet, 1, 1, pStrArrHeaderLines.Count-1, pResult.Count());
        using (var memoryStream = new MemoryStream())
        {
            pPageResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            pPageResponse.AddHeader("content-disposition", "attachment;  filename=" + pStrFileName + ".xlsx");
            excel.SaveAs(memoryStream);
            memoryStream.WriteTo(pPageResponse.OutputStream);
            pPageResponse.Flush();
            pPageResponse.End();
        }
    }


    public static void Export_AlignAndSetStyleForSheet(ExcelWorksheet pObjSheet, int pIntStartRow, int pIntStartCol, int pIntTotCols, int pIntTotRows)
    {
        pObjSheet.Cells.AutoFitColumns();
        ExcelRange objRange = pObjSheet.Cells[pIntStartRow, pIntStartCol, pIntStartRow, pIntTotCols + pIntStartCol];
        objRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
        objRange.Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
        objRange.Style.Font.Bold = true;
        objRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
        objRange.Style.Font.Color.SetColor(Color.White);
        objRange.Style.Fill.BackgroundColor.SetColor(Color.Black);
        objRange.Style.Border.Diagonal.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
        objRange.Style.Border.Diagonal.Color.SetColor(Color.Black);

        pObjSheet.Cells[pIntStartRow, pIntStartCol, pIntTotRows + pIntStartRow, pIntTotCols + pIntStartCol].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);
    }
}